<!-- src/components/Chart5.vue -->
<template>
  <div ref="chart" class="chart-container"></div>
</template>

<script>
import * as echarts from 'echarts';
import { fetchData } from '../Api/api.js';

export default {
  data() {
    return {
      topUsers: [],
      chart: null,
      updateInterval: null
    };
  },
  async mounted() {
    await this.loadData();
    this.initChart();
    // 每30秒刷新一次数据
    this.updateInterval = setInterval(this.loadData, 30000);
  },
  beforeDestroy() {
    if (this.updateInterval) {
      clearInterval(this.updateInterval);
    }
    if (this.chart) {
      this.chart.dispose();
    }
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    async loadData() {
      try {
        const data = await fetchData('getfive');
        this.topUsers = data;
        if (this.chart) {
          this.updateChart();
        }
      } catch (error) {
        console.error('Error fetching chart data:', error);
      }
    },
    initChart() {
      this.chart = echarts.init(this.$refs.chart);
      this.updateChart();
      window.addEventListener('resize', this.handleResize);
    },
    handleResize() {
      this.chart && this.chart.resize();
    },
    updateChart() {
      const colors = ['#5470C6', '#91CC75', '#FAC858', '#EE6666', '#73C0DE', '#3BA272', '#FC8452', '#9A60B4', '#EA7CCC'];

      // 计算总数用于百分比显示
      const total = this.topUsers.reduce((sum, user) => sum + user.senderMsgCnt, 0);

      const option = {
        title: {
          text: '今日消息发送排行榜',
          subtext: 'Top 10 活跃用户',
          left: 'center',
          textStyle: {
            color: '#2c3e50',
            fontSize: 22,
            fontWeight: 'bold',
            fontFamily: 'PingFang SC, Microsoft YaHei, sans-serif'
          },
          subtextStyle: {
            color: '#7f8c8d',
            fontSize: 14,
            fontFamily: 'PingFang SC, Microsoft YaHei, sans-serif'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: (params) => {
            const data = params[0];
            const percent = ((data.value / total) * 100).toFixed(1);
            return `
              <div style="font-weight:bold;margin-bottom:5px">${data.name}</div>
              <div style="display:flex;align-items:center">
                <span style="display:inline-block;width:10px;height:10px;background:${data.color};border-radius:2px;margin-right:5px"></span>
                <span>发送消息数: </span>
                <span style="font-weight:bold;margin-left:5px">${data.value}</span>
              </div>
              <div>占比: ${percent}%</div>
            `;
          },
          backgroundColor: 'rgba(255,255,255,0.95)',
          borderColor: '#e0e0e0',
          borderWidth: 1,
          textStyle: {
            color: '#333'
          },
          extraCssText: 'box-shadow: 0 4px 12px 0 rgba(0,0,0,0.1);border-radius: 4px;padding: 12px;'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          axisLine: {
            lineStyle: {
              color: '#e0e0e0'
            }
          },
          axisLabel: {
            color: '#7f8c8d'
          },
          splitLine: {
            lineStyle: {
              color: '#f5f5f5'
            }
          }
        },
        yAxis: {
          type: 'category',
          data: this.topUsers.map(user => user.userName),
          axisLine: {
            lineStyle: {
              color: '#e0e0e0'
            }
          },
          axisLabel: {
            color: '#7f8c8d',
            fontFamily: 'PingFang SC, Microsoft YaHei, sans-serif'
          },
          axisTick: {
            show: false
          }
        },
        series: [
          {
            name: '发送消息数',
            type: 'bar',
            data: this.topUsers.map((user, index) => ({
              value: user.senderMsgCnt,
              itemStyle: {
                color: colors[index % colors.length],
                borderRadius: [0, 4, 4, 0]
              }
            })),
            barWidth: '60%',
            label: {
              show: true,
              position: 'right',
              formatter: '{c}',
              color: '#2c3e50',
              fontFamily: 'PingFang SC, Microsoft YaHei, sans-serif'
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.3)'
              }
            },
            animationType: 'scale',
            animationEasing: 'elasticOut',
            animationDelay: function (idx) {
              return idx * 100;
            }
          }
        ],
        backgroundColor: '#fff',
        animationDuration: 1500,
        textStyle: {
          fontFamily: 'PingFang SC, Microsoft YaHei, sans-serif'
        }
      };

      this.chart.setOption(option, true);

      // 添加点击事件
      this.chart.on('click', (params) => {
        console.log('用户点击了:', params.name);
      });
    }
  }
};
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 450px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  padding: 15px;
  box-sizing: border-box;
}
</style>